package thread.demo.scheduleThreadPoolExecutor;

import java.util.concurrent.*;

public class ScheduleThreadPoolExecutorTest001 {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
    ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(3, new ThreadFactory() {
      @Override
      public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setName("schedule-thread-pool");
        return thread;
      }
    });
    
    scheduled.execute(() -> {
      System.out.println("这是一个立即执行函数");
    });
    
    // 这是一个延时队列
    scheduled.schedule(() -> {
      System.out.println("这是一个延时消息");
    }, 2, TimeUnit.SECONDS);
    
    // at 这是一个周期性任务
    // 周期时间：从任务启动开始计算 => m. 间隔时间 => n/ m > n => m  n > m => n
    scheduled.scheduleAtFixedRate(() -> {
      System.out.println("at task");
      System.out.println(System.currentTimeMillis());
      
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }, 0, 3, TimeUnit.SECONDS);
    
    // with 这是一个周期性任务
    // 间隔时间：任务执行时间 + 间隔时间
    scheduled.scheduleWithFixedDelay(() -> {
      System.out.println("with task");
      System.out.println(System.currentTimeMillis());
      
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }, 0, 3, TimeUnit.SECONDS);
    
    // 这是一个具有返回值的任务
    ScheduledFuture<String> result = scheduled.schedule(() -> {
      System.out.println("这是一个具有返回值的任务");
      return "r";
    }, 2, TimeUnit.SECONDS);
    System.out.println(result.get());
    
    scheduled.shutdown();
  }
}
